import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../layout/Layout.vue'
import ls from '@/utils/ls'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: import.meta.env.BASE_URL,
  routes: [
    {
      path: '*',
      redirect: '/404',
    },
    {
      path: '/',
      name: 'Home',
      meta: {
        title: '首页',
      },
      component: () => import('../views/Home/Home.vue'),
    },
    {
      path: '/404',
      name: 'P404',
      meta: {
        title: '404页面',
      },
      component: () => import('../views/Page404.vue'),
    },
    {
      path: '/403',
      name: 'P403',
      meta: {
        title: '403无权限',
      },
      component: () => import('../views/Page403.vue'),
    },
    {
      path: '/login',
      name: 'Login',
      meta: {
        title: '登录页',
      },
      component: () => import('../views/Login/Login.vue'),
    },
  ]
})

// 解决跳转同一个路由的报错方法
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


router.beforeEach((to, from, next) => {
  const rts = router.matcher.getRoutes()
  const hasName = rts?.some(v => v.name && v.name === to.name)
  // 跳转404
  if (!hasName) {
    next('/404')
  }
  
  next()
})

router.afterEach((to, from, next) => {
  document.title = `VTE - ${to.meta.title}`.replace(/\s-\sundefined$/, '')
})

export default router
